﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Text.Json;
using System.Threading.Tasks;

namespace ApplicationSentinelService
{
    public partial class ApplicationSentinelService : ServiceBase
    {
        private List<ProcessConfig> PCFG = new List<ProcessConfig>();
        public ApplicationSentinelService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            PCFG = LoadConfig("ApplicationConfig.json");
            if (PCFG.Count == 0)
            {
                Console.WriteLine("没有配置文件或配置文件为空。");
                return;
            }
            foreach (var config in PCFG)
            {
                if (config.Sentinel)
                {
                    Task.Run(() => MonitorProcess(config));
                }
                else
                {
                    Process[] processes = Process.GetProcessesByName(config.Name);
                    if (processes.Length == 0)
                    {
                        Console.WriteLine($"进程 {config.Name} 不存在，正在启动...");
                        WinAPI.PROCESS_INFORMATION procInfo;
                        WinAPI.StartProcessInSession0(config.Path + "\\" + config.Name + ".exe", config.Path, out procInfo, false, null, true);
                    }
                }
            }
        }
        private void MonitorProcess(ProcessConfig config)
        {
            while (true)
            {
                try
                {
                    Process[] processes = Process.GetProcessesByName(config.Name);
                    if (processes.Length == 0)
                    {
                        // 如果进程不存在，则启动它
                        Console.WriteLine($"进程 {config.Name} 不存在，正在启动...");
                        //Process.Start(new ProcessStartInfo
                        //{
                        //    FileName = config.Path,
                        //    Arguments = config.Arguments,
                        //    UseShellExecute = true
                        //});
                        WinAPI.PROCESS_INFORMATION procInfo;
                        WinAPI.StartProcessInSession0(config.Path + "\\"+ config.Name + ".exe", config.Path, out procInfo, false, null, true);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"监控进程 {config.Name} 时出错: {ex.Message}");
                }
                // 每隔5秒检查一次
                Task.Delay(1000).Wait();
            }
        }
        protected override void OnStop()
        {
        }


        private static List<ProcessConfig> LoadConfig(string configFilePath)
        {
            try
            {
                if (!File.Exists(configFilePath))
                {
                    Console.WriteLine($"配置文件不存在: {configFilePath}");
                    return new List<ProcessConfig>();
                }

                string json = File.ReadAllText(configFilePath);

                var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true // 忽略大小写
                };

                return JsonSerializer.Deserialize<List<ProcessConfig>>(json, options);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"读取配置文件出错: {ex.Message}");
                return new List<ProcessConfig>();
            }
        }
    }
    public class ProcessConfig
    {
        public string Name { get; set; }//应用程序名称
        public string Path { get; set; }//应用程序所在目录
        public bool Sentinel { get; set; }//是否启用哨兵
        public string Arguments { get; set; }//参数、描述
    }

}
